/**
 * This file is part of the dspace-poltman project http://www.poltman.com.
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of DuraSpace DSpace license detailed in the LICENSE and NOTICE 
 * files at the root of the source tree and available online at
 * http://www.dspace.org/license/
 * 
 */
package com.poltman.dscentral.register;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.dspace.core.Context;
import org.dspace.core.Utils;
import org.dspace.eperson.AccountManager;
import org.dspace.eperson.EPerson;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Label;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;

import com.poltman.dscentral.core.webappinit.WebAppInit;
import com.poltman.dscentral.db.entity.dspace.EPersonEntity;
import com.poltman.dscentral.db.entity.pm.BaseUserEntity;
import com.poltman.dscentral.db.service.dspace.EPersonService;
import com.poltman.dscentral.db.service.dspace.RegistrationdataService;
import com.poltman.dscentral.db.service.pm.BaseUserService;

/**
 * 
 * @author Zbigniew Ciok; z.ciok@poltman.com
 * @version $Revision: 1821 $
 *
 */
@SuppressWarnings("rawtypes")
public class RegistrationFormController extends GenericForwardComposer {

	private static final long serialVersionUID = -894406755719112842L;
	
	private static Logger log = Logger.getLogger(RegistrationFormController.class);
	
	private Label errorMsgLabel;
	private Textbox tokenTxb;
	private Textbox password1Txb;
	private Textbox password2Txb;
	
	private Grid passwordGrid;
	
	private String token = "";
	private EPersonService epersonService = null;
	private EPersonEntity epersonEnt = null;
	private BaseUserEntity baseUser = null;
	
	private boolean passwordAuthentication = false;

	@SuppressWarnings("unchecked")
	@Override
    public void doAfterCompose(org.zkoss.zk.ui.Component comp) throws Exception {
    	super.doAfterCompose(comp);
		this.token = (tokenTxb.getValue() == null) ? "" : tokenTxb.getValue();
		
		if ("".equals(this.token)) {
			log.info("RegistrationFormController: token == null.");
			this.errorMessageAndRedirect("token == null.");
			return;
		}    
		
		Context context = (Context) SpringUtil.getBean("context");
		
		try {
			//We have a token. Find out who the it's for
			String email = AccountManager.getEmail(context, token);		
			if (email == null) {
				log.info("Invalid token.");
				this.errorMessageAndRedirect("Invalid token.");
				return;
			}
			this.epersonService = (EPersonService)SpringUtil.getBean("epersonService");
			this.epersonEnt = this.epersonService.findByEmail(email);
			BaseUserService baseUserService = (BaseUserService) SpringUtil.getBean("baseUserService");
			
			this.baseUser = (BaseUserEntity) baseUserService.findByEpersonId(this.epersonEnt.getEpersonId());
		} catch (Exception e) {
			log.error("doAfterCompose() (01): ", e);
			this.errorMessageAndRedirect("Confirm Registration Error (01).");
			return;
		}
		
		if (this.baseUser == null) {
			log.error("doAfterCompose() (02)");
			this.errorMessageAndRedirect("Confirm Registration Error (02).");
			return;
			
		}	
		
		//TODO: "Password"
		if ("Password".equals(this.baseUser.getDscAuthenticationMethod())) {
			this.passwordAuthentication = true;
			this.passwordGrid.setVisible(true);
		} else {
			this.passwordAuthentication = false;
			this.passwordGrid.setVisible(false);
		}
    }
	
	/**
	 * 
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void onClick$confirmBtn() throws Exception {
		String pass1 = (password1Txb.getValue() == null) ? "" : password1Txb.getValue();
		String pass2 = (password2Txb.getValue() == null) ? "" : password2Txb.getValue();
		
		if (this.passwordAuthentication) {
			this.passwordGrid.setVisible(true);
			if (("".equals(pass1)) || ("".equals(pass2))) {
				errorMsgLabel.setVisible(true);
				return;
			} else {
				if ((pass1.length() < 6) || (pass2.length() < 6)) {
					errorMsgLabel.setVisible(true);
					return;					
				}
				errorMsgLabel.setVisible(false);
			}
		
			if (!pass1.equals(pass2)) {
				errorMsgLabel.setVisible(true);
				return;
			} else {
				errorMsgLabel.setVisible(false);
			}
		//LDAP/X.509
		} else {
			this.passwordGrid.setVisible(false);
		}
		
		try {
			this.epersonEnt.setCanLogIn(true);
			
			if (this.passwordAuthentication) {
				String encoded = Utils.getMD5(pass1);
				this.epersonEnt.setPassword(encoded);
			} else {
				this.epersonEnt.setPassword(null);
			}
			
			this.epersonService.save(this.epersonEnt);
		
			RegistrationdataService registrationdataService = (RegistrationdataService) SpringUtil.getBean("registrationdataService");
			registrationdataService.deleteByToken(this.token);
		} catch (Exception e) {
			log.error("onClick$confirmBtn() (01)", e);
			this.errorMessageAndRedirect("onClick$confirmBtn() (01)");
			return;			
		}
		
		this.exit();
	}
	
	/**
	 * Closes current session and redirects to DSCentral
	 */
	@SuppressWarnings("static-access")
	private void exit() {
		HttpSession s = (HttpSession)Sessions.getCurrent().getNativeSession();
		s.invalidate();
		Sessions.getCurrent().invalidate();
		Context context = (Context) SpringUtil.getBean("context");
		context.clear();
		String dscentralUrl = WebAppInit.getInstance().getDscentralUrl();
		Executions.sendRedirect(dscentralUrl);
	}
	
	@SuppressWarnings("unchecked")
	private void errorMessageAndRedirect(String msg) {
		Messagebox.show(msg, "DSCentral Error", Messagebox.OK, Messagebox.ERROR, new org.zkoss.zk.ui.event.EventListener() {
			@SuppressWarnings("static-access")
			public void onEvent(Event evt) {
				String dscentralUrl = WebAppInit.getInstance().getDscentralUrl();
				Executions.sendRedirect(dscentralUrl);
			}
		});
		
	}
}
